<template>
  <div
    class="global-background"
    v-if="userProfile?.subscription === 'PREMIUM' && userProfile?.backgroundUrl"
    :style="{ backgroundImage: `url(${userProfile.backgroundUrl})` }"
  />
  <el-container v-if="authStore.isAuthenticated && !isMobile" class="app-layout">
    <el-aside class="sidebar" width="200px">
      <div class="logo">个性化教育系统</div>
      <el-menu :default-active="activeMenu" class="el-menu-vertical" router>
        <el-menu-item index="/dashboard">
          <el-icon><House /></el-icon>
          <span>仪表盘</span>
        </el-menu-item>

        <el-sub-menu v-if="authStore.isStudent" index="student-menu">
          <template #title>
            <el-icon><Notebook /></el-icon>
            <span>我的学习</span>
          </template>
          <el-menu-item index="/my-classroom">我的班级</el-menu-item>
          <el-menu-item index="/practice">个性化练习</el-menu-item>
          <el-menu-item index="/error-notebook">我的错题本</el-menu-item>
          <el-menu-item index="/ability-analysis">能力分析</el-menu-item>
        </el-sub-menu>

        <el-sub-menu v-if="authStore.isTeacher" index="teacher-menu">
          <template #title>
            <el-icon><DataAnalysis /></el-icon>
            <span>教学管理</span>
          </template>
          <el-menu-item index="/teacher/classes">班级管理</el-menu-item>
          <el-menu-item index="/teacher/dashboard">学情分析</el-menu-item>
          <el-menu-item index="/teacher/upload-question">上传题目</el-menu-item>
        </el-sub-menu>

        <el-menu-item v-if="authStore.isAdmin" index="/admin/users">
          <el-icon><User /></el-icon>
          <span>用户管理</span>
        </el-menu-item>
        <el-sub-menu v-if="authStore.isAdmin" index="/admin/question-bank">
          <template #title>
          <el-icon><Notebook /></el-icon>
          <span>题库管理</span>
          </template>
          <el-menu-item index="/admin/upload-question">上传题目</el-menu-item>
          <el-menu-item index="/admin/upload-knowledge-points">上传知识点</el-menu-item>
          <el-menu-item index="/admin/pending-question">审核题目</el-menu-item>
          <el-menu-item index="/admin/approved-question">查看题库</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header class="app-header">
        <div></div>
        <div class="user-info">
          <span>你好, {{ userProfile?.nickname || '游客' }}</span>
          <el-dropdown>
            <el-avatar
              v-if="userProfile?.avatar"
              :src="userProfile.avatar"
              style="width: 32px; height: 32px"
            />
            <el-avatar v-else :icon="UserFilled" style="width: 32px; height: 32px" />
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="goToProfile">个人信息</el-dropdown-item>
                <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main>
        <router-view />
      </el-main>
    </el-container>
  </el-container>

  <!-- 移动端布局 -->
  <el-container v-else-if="authStore.isAuthenticated && isMobile" class="app-mobile-layout">
    <el-header class="mobile-header">
      <el-button @click="mobileMenuVisible = true" circle class="mobile-menu-button">
        <svg
          width="20"
          height="20"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <line x1="3" y1="7" x2="21" y2="7"></line>
          <line x1="3" y1="12" x2="21" y2="12"></line>
          <line x1="3" y1="17" x2="21" y2="17"></line>
        </svg>
      </el-button>
      <span class="mobile-title">个性化教育系统</span>
      <el-dropdown>
        <el-avatar
          v-if="userProfile?.avatar"
          :src="userProfile.avatar"
          style="width: 32px; height: 32px"
        />
        <el-avatar v-else :icon="UserFilled" style="width: 32px; height: 32px" />
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goToProfile">个人信息</el-dropdown-item>
            <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-header>

    <el-drawer v-model="mobileMenuVisible" direction="ltr" size="50%">
      <el-menu :default-active="activeMenu" class="el-menu-vertical" router>
        <el-menu-item index="/dashboard">
          <el-icon><House /></el-icon>
          <span>仪表盘</span>
        </el-menu-item>

        <el-sub-menu v-if="authStore.isStudent" index="student-menu">
          <template #title>
            <el-icon><Notebook /></el-icon>
            <span>我的学习</span>
          </template>
          <el-menu-item index="/my-classroom">我的班级</el-menu-item>
          <el-menu-item index="/practice">个性化练习</el-menu-item>
          <el-menu-item index="/error-notebook">我的错题本</el-menu-item>
          <el-menu-item index="/ability-analysis">能力分析</el-menu-item>
        </el-sub-menu>

        <el-sub-menu v-if="authStore.isTeacher" index="teacher-menu">
          <template #title>
            <el-icon><DataAnalysis /></el-icon>
            <span>教学管理</span>
          </template>
          <el-menu-item index="/teacher/classes">班级管理</el-menu-item>
          <el-menu-item index="/teacher/dashboard">学情分析</el-menu-item>
          <el-menu-item index="/teacher/upload-question">上传题目</el-menu-item>
        </el-sub-menu>

        <el-sub-menu v-if="authStore.isAdmin" index="/admin/question-bank">
          <template #title>
            <el-icon><Notebook /></el-icon>
            <span>题库管理</span>
          </template>
          <el-menu-item index="/admin/upload-question">上传题目</el-menu-item>
          <el-menu-item index="/admin/upload-knowledge-points">上传知识点</el-menu-item>
          <el-menu-item index="/admin/pending-question">审核题目</el-menu-item>
          <el-menu-item index="/admin/approved-question">查看题库</el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-drawer>

    <el-main>
      <router-view />
    </el-main>
  </el-container>

  <!-- 未登录时 -->
  <div v-else>
    <router-view />
  </div>
</template>


<script lang="ts" setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from './stores/authStore'
import { DataAnalysis, House, Notebook, User, UserFilled } from '@element-plus/icons-vue'
import { apiClient } from '@/api'
import { ElMessage } from 'element-plus'
import { eventBus } from '@/api/eventbus.ts'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const activeMenu = computed(() => route.path)

interface UserDetailResponseDto {
  userId: number
  username: string
  nickname: string
  email: string
  role: 'STUDENT' | 'TEACHER' | 'ADMIN'
  subscription: 'NORMAL' | 'PREMIUM'
  backgroundUrl?: string
  active: boolean
  createdAt: string
  avatar: string
}

const userProfile = ref<UserDetailResponseDto | null>(null)

const isMobile = ref(false)
const mobileMenuVisible = ref(false)

function checkIfMobile() {
  isMobile.value = window.innerWidth < 768
}

function goToProfile() {
  router.push('/user/profile')
}

const loadUserProfile = async () => {
  try {
    const res = await apiClient.get<UserDetailResponseDto>('/user/profile')
    userProfile.value = res.data
  } catch (e) {
    ElMessage.error('加载用户信息失败')
  }
}

const logout = async () => {
  try {
    await authStore.logout()
  } catch (error) {
    ElMessage.error('退出登录失败')
  }
}

const onAvatarUpdated = (newAvatar: string) => {
  if (userProfile.value) {
    userProfile.value.avatar = newAvatar
  }
}

const onBackgroundUpdated = (newBackground: string) => {
  if (userProfile.value) {
    userProfile.value.backgroundUrl = newBackground
  }
}

onMounted(() => {
  eventBus.on('avatar-updated', onAvatarUpdated)
  eventBus.on('background-updated', onBackgroundUpdated)
  authStore.initialize()
  checkIfMobile()
  window.addEventListener('resize', checkIfMobile)
})

onBeforeUnmount(() => {
  eventBus.off('avatar-updated')
  eventBus.off('background-updated')
  window.removeEventListener('resize', checkIfMobile)
})

watch(
  () => authStore.isAuthenticated,
  async (isAuthenticated) => {
    if (isAuthenticated) {
      await loadUserProfile()
    } else {
      userProfile.value = null
    }
  },
  { immediate: true }
)
</script>

<style>
/* 全局样式 */
body {
  margin: 0;
  font-family:
    'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial,
    sans-serif;
}
</style>

<style scoped>

.app-layout {
  height: 100vh;
}

.sidebar {
  background-color: #545c64;
  color: #fff;
}

.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  color: #fff;
  background-color: #434a50;
}

.el-menu-vertical {
  border-right: none;
  background-color: #545c64;
}

.el-menu-item,
.el-sub-menu :deep(.el-sub-menu__title) {
  background-color: #545c64 !important;
  color: #fff !important;
}

.el-menu-item:hover,
.el-sub-menu :deep(.el-sub-menu__title:hover) {
  background-color: #434a50 !important;
  color: #ffd04b !important;
}

.el-menu-item.is-active,
.el-sub-menu :deep(.el-sub-menu__title.is-active) {
  background-color: #434a50 !important;
  color: #ffd04b !important;
}

.el-menu-item el-icon,
.el-sub-menu :deep(.el-sub-menu__title) el-icon {
  color: inherit !important;
  background: transparent !important;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dcdfe6;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info span {
  margin-right: 15px;
}

.el-main {
  background-color: #f0f2f5;
  padding: 20px;
}

/* === 移动端样式 === */
.app-mobile-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.mobile-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
  padding: 0 12px;
  background-color: #545c64;
  color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.mobile-title {
  font-size: 18px;
  font-weight: bold;
}

/* 按钮样式让图标保持白色 */
.el-button.is-circle {
  color: #fff;
  border: none;
  background-color: transparent;
}

/* 移动端抽屉菜单 */
.el-drawer .el-menu {
  background-color: #545c64;
  border-right: none;
  padding-top: 20px;
}

.el-drawer .el-menu-item,
.el-drawer :deep(.el-sub-menu__title) {
  background-color: #545c64 !important;
  color: #fff !important;
}

.el-drawer .el-menu-item:hover,
.el-drawer :deep(.el-sub-menu__title:hover) {
  background-color: #434a50 !important;
  color: #ffd04b !important;
}

.el-drawer .el-menu-item.is-active,
.el-drawer :deep(.el-sub-menu__title.is-active) {
  background-color: #434a50 !important;
  color: #ffd04b !important;
}

.el-drawer .el-icon {
  color: inherit;
}

.el-drawer__body {
  padding: 0;
}


/* 移动端主内容区域 */
.app-mobile-layout .el-main {
  padding: 16px;
  background-color: #f0f2f5;
  flex-grow: 1;
  overflow-y: auto;
}

.mobile-header .el-button.is-circle {
  background-color: #ffd04b;
  color: #545c64;
  border: none;
  box-shadow: 0 2px 6px rgb(255 208 75 / 0.5);
  padding: 6px;
  font-size: 18px;
}

.mobile-header .el-button.is-circle:hover {
  background-color: #ffec7a;
  color: #434a50;
}

.global-background {
  position: fixed;
  inset: 0;
  z-index: 9999;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  filter: brightness(0.8);
  pointer-events: none;
  opacity: 0.1;
}

</style>

